/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.flexengine.utils;

import com.flexengine.logger.Logger;
import java.util.Scanner;

/**
 * @author Luann R. Athayde
 * @version 1.0
 * @since 1.0
 */
public abstract class FlexEngineConsole implements Runnable {
    
    private Thread  tFlexEngineConsole;
    
    private String  consoleUser;
    private boolean waiting;
    private Scanner sc;

    public FlexEngineConsole(String consoleUser) {
        this.consoleUser = consoleUser;
        this.waiting = false;
        this.sc      = null;
    }
    
    public void waitForCommands() {
        if( !waiting ) {
            tFlexEngineConsole = null;
            tFlexEngineConsole = new Thread(this, this.getClass().getSimpleName());
            //tFlexEngineConsole.setDaemon(true);
            tFlexEngineConsole.start();
        }
    }
    
    @Override
    public void run() {
        try {
            waiting = true;
            sc = new Scanner(System.in);
            while( waiting ) {
                System.out.print(consoleUser+"@"+
                        getClass().getSimpleName()+
                        ":~$: ");
                String cmd = sc.nextLine();
                execute(cmd);
                //System.out.print("\n");
            }
        } catch(Exception e) {
            Logger.logMessage(getClass().getSimpleName()+" - run(): "+e);
        }
    }
    
    public abstract void execute(String cmd);

    public boolean isWaiting() {
        return waiting;
    }

    public void stopWaiting() {
        waiting = false;
        if( tFlexEngineConsole!=null ) {
            tFlexEngineConsole.interrupt();
        }
        tFlexEngineConsole = null;
        if( sc!=null ) {
            sc.close();
        }
        sc = null;
        Logger.logMessage("\n"+getClass().getSimpleName()+" - Waiting for commands stoped...");
    }

    public String getConsoleUser() {
        return consoleUser;
    }

    public void setConsoleUser(String consoleUser) {
        this.consoleUser = consoleUser;
    }
    
}
